<template>
  <div class="inventory-alert-container">
    <!-- 搜索条件区域 -->
    <div class="search-section">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
        <!-- 搜索条件 -->
        <div class="search-row">
          <el-form-item label="货品" prop="productName">
            <el-input 
              v-model="searchForm.productName" 
              placeholder="请输入货品名称/编号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <el-form-item label="货品类型" prop="productTypeId">
            <el-select 
              v-model="searchForm.productTypeId" 
              placeholder="请选择"
              clearable
              style="width: 150px"
            >
              <el-option label="电子产品" value="电子产品" />
              <el-option label="家电" value="家电" />
              <el-option label="服装" value="服装" />
              <el-option label="食品" value="食品" />
              <el-option label="家具" value="家具" />
              <el-option label="化妆品" value="化妆品" />
              <el-option label="鞋类" value="鞋类" />
              <el-option label="配饰" value="配饰" />
              <el-option label="玩具" value="玩具" />
              <el-option label="书籍" value="书籍" />
              <el-option label="运动器材" value="运动器材" />
              <el-option label="饮品" value="饮品" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="仓库名称" prop="limitStatus">
            <el-select 
              v-model="searchForm.limitStatus" 
              placeholder="请选择"
              clearable
              style="width: 120px"
            >
              <el-option label="仓库一" value="仓库一" />
              <el-option label="仓库二" value="仓库二" />
              <el-option label="仓库三" value="仓库三" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="当前库存" prop="currentInventoryRange">
            <el-input 
              v-model="searchForm.currentInventoryMin" 
              placeholder="请输入"
              style="width: 120px"
            />
          </el-form-item>
        </div>
        
        <!-- 操作按钮 -->
        <div class="button-row">
          <el-button @click="handleExport" type="default">导出</el-button>
          <el-button @click="handleRefresh" type="default">刷新</el-button>
          <el-button @click="handleReset" type="default">重置</el-button>
          <el-button @click="handleSearch" type="primary">查询</el-button>
        </div>
      </el-form>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        v-loading="loading"
        style="width: 100%"
        border
        stripe
      >
       "id": 0,
      "product_Id": 1,
      "productNo": "P202507316107",
      "productName": "可口可乐",
      "productTypeId": "食品",
      "productModel": "500ml",
      "unitName": "瓶",
      "inventory": "仓库一",
      "location": "库位一",
      "current_Inventory": 300,
      "available_Inventory": 500,
      "waitIn": 100,
      "waitOut": 50,
      "upperlimit": 500,
      "lowerlimit": 10
        <el-table-column type="selection" width="55" />
        <el-table-column prop="index" label="序号" width="80" />
        <el-table-column prop="productNo" label="货品编号" width="120" />
        <el-table-column prop="productName" label="货品名称" width="150" />
        <el-table-column prop="productModel" label="规格型号" width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="productTypeId" label="货品类型" width="120" />
        <el-table-column prop="current_Inventory" label="当前库存" width="100" />
        <el-table-column prop="lowerlimit" label="库存下限" width="100" />
        <el-table-column prop="upperlimit" label="库存上限" width="100" />
        <el-table-column prop="belowLowerLimit" label="低于下限" width="120">
          <template #default="scope">
            <span 
              :class="getBelowLimitClass(scope.row)"
              :style="{ color: getBelowLimitColor(scope.row) }"
            >
              {{ getBelowLimitPercentage(scope.row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="aboveUpperLimit" label="高于上限" width="120">
          <template #default="scope">
            <span 
              :class="getAboveLimitClass(scope.row)"
              :style="{ color: getAboveLimitColor(scope.row) }"
            >
              {{ getAboveLimitPercentage(scope.row) }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TZRead } from '@/http/interceptors'

// 搜索表单数据
const searchForm = reactive<{
  productName: string
  productTypeId: string
  limitStatus: string
  currentInventoryMin: string
  currentInventoryMax: string
}>({
  productName: '',
  productTypeId: '',
  limitStatus: '',
  currentInventoryMin: '',
  currentInventoryMax: ''
})

// 分页数据
const pagination = reactive<{
  pageIndex: number
  pageSize: number
  total: number
}>({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<any[]>([])
const loading = ref(false)

// 表单引用
const searchFormRef = ref<any>()

// 查询数据
const loadData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params: any = {
      Pageindex: pagination.pageIndex,
      Pagesize: pagination.pageSize,
      ProductName: searchForm.productName || undefined,
      ProductTypeId: searchForm.productTypeId || undefined,
      Inventory: searchForm.limitStatus || undefined,
      Current_Inventory: searchForm.currentInventoryMin ? parseInt(searchForm.currentInventoryMin) : undefined
    }
    
    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete (params as any)[key]
      }
    })

    // 调用库存预警查询API接口
    const res = await TZRead.get("/api/Product/warehouse-list", { params })
    
    if (res.data.code === 200) {
      // 处理数据：添加序号
      const processedData = (res.data.pageData as any[]).map((item: any, index: number) => {
        return {
          ...item,
          index: (pagination.pageIndex - 1) * pagination.pageSize + index + 1
        }
      })
      
      tableData.value = processedData
      pagination.total = res.data.totalCount
      
      ElMessage.success('查询成功')
    } else {
      ElMessage.error(res.data.message || '查询失败')
    }
  } catch (error: any) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleSearch = () => {
  pagination.pageIndex = 1
  loadData()
}

// 重置按钮
const handleReset = () => {
  searchFormRef.value?.resetFields()
  pagination.pageIndex = 1
  loadData()
}

// 刷新按钮
const handleRefresh = () => {
  loadData()
}

// 导出按钮
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 分页大小改变
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.pageIndex = 1
  loadData()
}

// 当前页改变
const handleCurrentChange = (page: number) => {
  pagination.pageIndex = page
  loadData()
}

// 低于下限样式处理
const getBelowLimitClass = (row: any) => {
  const current = row.current_Inventory || 0
  const lower = row.lowerlimit || 0
  return current < lower ? 'warning-text' : 'normal-text'
}

const getBelowLimitColor = (row: any) => {
  const current = row.current_Inventory || 0
  const lower = row.lowerlimit || 0
  return current < lower ? '#f56c6c' : '#67c23a'
}

const getBelowLimitPercentage = (row: any) => {
  const current = row.current_Inventory || 0
  const lower = row.lowerlimit || 0
  if (lower > 0 && current < lower) {
    // 当库存低于下限时，计算低于的数量占下限的百分比
    const belowAmount = lower - current
    const percentage = (belowAmount / lower * 100).toFixed(2)
    return `${percentage}%`
  }
  return '0.00%'
}

// 高于上限样式处理
const getAboveLimitClass = (row: any) => {
  const current = row.current_Inventory || 0
  const upper = row.upperlimit || 0
  return current > upper ? 'warning-text' : 'normal-text'
}

const getAboveLimitColor = (row: any) => {
  const current = row.current_Inventory || 0
  const upper = row.upperlimit || 0
  return current > upper ? '#f56c6c' : '#67c23a'
}

const getAboveLimitPercentage = (row: any) => {
  const current = row.current_Inventory || 0
  const upper = row.upperlimit || 0
  if (upper > 0 && current > upper) {
    // 当库存高于上限时，计算高于的数量占上限的百分比
    const aboveAmount = current - upper
    const percentage = (aboveAmount / upper * 100).toFixed(2)
    return `${percentage}%`
  }
  return '0.00%'
}

// 页面初始化
onMounted(() => {
  // 加载数据
  loadData()
})
</script>

<style scoped>
.inventory-alert-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  width: 100%;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}

.button-row {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination-section {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.warning-text {
  font-weight: bold;
}

.normal-text {
  color: #67c23a;
}

:deep(.el-form-item) {
  margin-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-table) {
  border-radius: 8px 8px 0 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}
</style> 